package com.ncmmall.api.utils;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;

/**
 * 解密
 *
 * @author linxs
 * @date 2019-07-24 17:49
 */
@Slf4j
public class AESUtils {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES解密
     *
     * @param content 密文
     */
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) {

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");

            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(ivByte));

            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, params);
            return cipher.doFinal(content);

        } catch (Exception e) {
            log.error("[AES解密异常]", e);
            throw new IllegalArgumentException("AES解密异常");
        }
    }

}